﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
using SmartParking.Entities;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SmartParking.ORM.SmartParkingSqlLiteEntity
{
    public class SmartParkingContext : DbContext
    {
        public SmartParkingContext(DbContextOptions<SmartParkingContext> options)
            : base(options)
        {

        }

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            if (!optionsBuilder.IsConfigured)
            {
                optionsBuilder.UseSqlite("Data Source=smartparking.db");
            }
            base.OnConfiguring(optionsBuilder);
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            ValueConverter iconValueConverter =
                new ValueConverter<string, string>(
                    // 页面→数据库的转换
                    PageToData => ((int)PageToData.ToArray()[0]).ToString("x"),
                    // 数据库→页面的转换
                    DataToPage => DataToPage == null ? "" : ((char)int.Parse(DataToPage, NumberStyles.HexNumber)).ToString()
                    );
            modelBuilder.Entity<SysMenu>()
                .Property(m => m.MenuIcon)
                .HasConversion(iconValueConverter);

            base.OnModelCreating(modelBuilder);
        }

        public virtual DbSet<SysUser> SysUser { get; set; }
        public virtual DbSet<SysMenu> SysMenu { get; set; }
    }
}
